package org.misalen.web.service.aop;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * 切片Log
 * 
 * @author guochao
 *
 */
@Component
@Aspect
public class LoggerAspect {

	private static final Logger logger = Logger.getLogger(LoggerAspect.class);

	@Before("execution(* *..controllers*..*(..))")
	public void doBefore(JoinPoint jp) {
		
	}

	@After("execution(* *..controllers*..*(..))")
	public void doAfter(JoinPoint jp) {
	}

	@Around("execution(* *..controllers*..*(..))")
	public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
		return pjp.proceed();
	}

	@AfterThrowing(pointcut = "execution(* *..controllers*..*(..))", throwing = "ex")
	public void doThrowing(JoinPoint jp, Throwable ex) {
		StringBuffer log = new StringBuffer();
		log.append(" #### ");
		log.append(jp.getTarget().getClass().getName());
		log.append(".");
		log.append(jp.getSignature().getName());
		log.append("[throw exception]");
		log.append(ex.getMessage());
		logger.info(log.toString());

		StackTraceElement[] elements = ex.getStackTrace();

		for (StackTraceElement element : elements) {
			logger.error(element.toString());
		}
	}
}
